package com.example.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.dao.BoomRepository;
import com.example.demo.dao.SourceRepository;
import com.example.demo.model.Account;
import com.example.demo.model.JieDaiBao;
import com.example.demo.model.entity.Boom;
import com.example.demo.model.entity.Source;
import com.example.demo.service.IJieDaiBaoService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * Created by Administrator on 2018/1/14.
 */
@Service
public class JieDaiBaoService implements IJieDaiBaoService {

    private RestTemplate client = new RestTemplate();

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    SourceRepository sourceRepository;

    @Autowired
    BoomRepository boomRepository;

    @Override
    public List<JieDaiBao> getJieDaiBaoList(List<String> phoneList) {
        List<Account> accountList = initAccount();
        List<Account> useList = new ArrayList<>();
        useList.addAll(accountList);
        List<JieDaiBao> data = new ArrayList<>();
        while (!CollectionUtils.isEmpty(useList)) {
            Account account = useList.get(0);
            String accessToken = loginRegister(account);
            for (Iterator it = phoneList.iterator(); it.hasNext(); ) {
                String p = (String) it.next();
                try {
                    JSONObject result = searchMember(account, accessToken, p);
                    System.out.println("end:" + p);
                    it.remove();
                    JSONArray array = result.getJSONObject("data").getJSONArray("memberList");
                    if (array != null) {
                        JSONObject guest = guest(account, array.getJSONObject(0).getString("memberID"), accessToken);
                        boolean flag = getAuthShowList(account, accessToken, array.getJSONObject(0).getString("memberID"));
                        if (flag) {
                            JieDaiBao jieDaiBao = new JieDaiBao();
                            jieDaiBao.setPhone(p);
                            jieDaiBao.setName(guest.getJSONObject("data").getJSONObject("memberInfo").getString("memberName"));
                            jieDaiBao.setBorrowTip(guest.getJSONObject("data").getJSONObject("memberInfo").getJSONArray("borrowTip").getJSONObject(0).getString("text"));
                            data.add(jieDaiBao);
                        }
                    }
                } catch (Exception e) {
                    useList.remove(account);
                }
            }
        }
        return data;
    }

    @Override
    public void importData(List<String> phoneList) {
//        for (String p : phoneList) {
//            Source source = new Source();
//            source.setSourceId(UUID.randomUUID().toString());
//            source.setCreateTime(new Date(System.currentTimeMillis()));
//            source.setPhone(p);
//            sourceRepository.save(source);
//        }
        timer();
    }

    @Override
    public List<Boom> getBoomListByDate(String date) {
        String sql = "SELECT * FROM t_boom WHERE DATE_FORMAT(create_time, '%Y-%m-%d') = ?";
        List<Boom> boomList = jdbcTemplate.queryForList(sql, Boom.class, date);
        return boomList;
    }

    private List<Account> initAccount() {
        List<Account> accountList = new ArrayList<>();
        Account a1 = new Account();
        a1.setPhone("18150192123");
        a1.setPassword("j4z9WkTHdE2+0meRH5zXxTBQcDScCNhD0TEOxYeu6/mV8QHQl9KroeUG4PJY2vUf663Fan5eSLoNZuHqCzqKd4+8QbYE8w1ox3PYukD4246SqzPLKh9i/rGzZBCv2ILPNp3m63dp3PiWulhC5GXwsJYTdBCgAqCzqBwBTOA8LEM=");
        a1.setMemberId("785250522566184968");

        Account a2 = new Account();
        a2.setPhone("13110794581");
        a2.setPassword("V1eIY18ah+CuPXcYMugx4LR/noJKCUvJOWlqruo88wTex4De/1KkD79sQwWOL5gc/sMYc8k3V7DLd+9NZqLYEd4/4a8sTEpkE2jGrbj5GStL6XCj0BlwS7khOc3goPQtH2UuCPY4noTnv0Oh9eLqUr1YtlcQ25m6n8wQzD4qAwg=");
        a2.setMemberId("834090057252945923");

        Account a3 = new Account();
        a3.setPhone("13115915497");
        a3.setPassword("EWhkUkrrkuMV3GooljtZq4zXNI0CIRPM+l8YzG7792ZoLc2qNXYQN8yjGG/o0YbzGrAczUHasWbbO2sOjZLsPaA3xC/AfnNPh6oy8Ulp01ISomfKNpDep2ews7U8ybyx7YDrMOpG/MwoX6i60GyGXhrYpsIljfBwPtPsTV/EC7o=");
        a3.setMemberId("806909626309095427");

//        Account a4 = new Account();
//        a4.setPhone("13115900740");
//        a4.setPassword("On1PZBlAoNBG4Dmz6LABeyNVTmD5yid9S1CftHITwdGH1SEwUrXYXfigKfnvGkmMnuqBcZN8R65qq7kOT1KfVh5pYvRvfinVsgQsbSU1hqz2yEgn6zad7qPNZvY/xm761l15FL7JuL/JiX1MUolzJWgTg5GN7/mRKvJQ9NaDezk=");
//        a4.setMemberId("834137099945861129");

        Account a5 = new Account();
        a5.setPhone("17135729920");
        a5.setPassword("Mdv127UPpzsET8FYp3YBo56MD5QdOnFgf8VwHP9pd0DZOlj94F5GXVYg6j9T55CDGe9egFyN1mfxpMuFv8JzjyfPcx8/QlmlKrt5P05kgimK9RkoKdbPuOxjwE7TQFJyXwpLYwM6zkkNTkmoYgymHhTKUdnpxmqRZzhp1I6H6Lw=");
        a5.setMemberId("834138624965435400");

        Account a6 = new Account();
        a6.setPhone("17120301703");
        a6.setPassword("of5eDQR0lvSNLb4ye8Qgu/BSXkF0nHjifjQBDdeH3SRqaIwWUDsoDPfr4Z3XNmyMtIZBUn9FgGddBg2By0+L3577LUr9PWZ4trU80MUiSkMhBqGIfy3N4rYOFCV0Gca5S7ZFoW86XXbOjUzxdRq23hGoWxK0xppZEN6LaNvZLK0=");
        a6.setMemberId("834139550799331336");

        Account a7 = new Account();
        a7.setPhone("17058006913");
        a7.setPassword("YK6CcSUthJAgapEJRMkqkMBwUae3C0vmhzF9pbU+oH1UGkSjwJklJK0MsC0y7DowNEsjQVb/Pt/lnkqLbJoU1Lts30vOxSwXJyE+io2MZiXeFcvLzMeNbjmdYO8blgEGgF0IH8JyAk/N6YMCxXTFOaHkNif5T+cZPA6gw8KTz2A=");
        a7.setMemberId("834140409239138310");

        Account a8 = new Account();
        a8.setPhone("17120301631");
        a8.setPassword("egXOHwCxFtEt9bVAlcm76IwDQDUllUhe+lRmc/CAb+80+I4hNCr8C29326Y5Ef6MP1I72tlieNeUxr/6QP1Lc8RnNMeSYenKwxRbSp925WNMDXw53E7F+HTPW7NXLZ1/teJIfFjbUj+Ny6HPUTGfbO4OZ0kdnIYO2M7Q44zynsM=");
        a8.setMemberId("834141783230201856");

        Account a9 = new Account();
        a9.setPhone("17120301638");
        a9.setPassword("J8Cxo223tzPq3eHgEP4hMPsmYYTy501mRgjiI7s/quSsaVLQsqYBUggfmHGUM43DCD9suGnvMChSGaVapQtx0TrUkQwRGFlBCT2gK1Ern1beA+QB/AJYzdZVlFhVDUEq14TSS11i/QV5Wy47+6sLy9zSdmXbceosByHGlzVgjCU=");
        a9.setMemberId("835536192467316744");

        Account a10 = new Account();
        a10.setPhone("17135729252");
        a10.setPassword("O05+FWOyg16kAB8fYPRV566IIeNdjc8XPXDqu120O3p2fxxA92BxOFyTriJ2ukBT3N+xhjENTh7Be6qU2iYxGTw9+YLmL7IFOzjW0BSUrMAObqyMgBkLLvDqWUy6CpxWjZTh1Os1RNREFN1ruB80wHwEFk1s/uye1ytD7nHyJzU=");
        a10.setMemberId("834140590743445504");

        Account a11 = new Account();
        a11.setPhone("17135725865");
        a11.setPassword("horCrPp+wuqeXToozKsBs4S+eQPC28Ugkg3hoEiFWgajIsdd2trHjh53pwB6Cu7dLv+7S4LKb1A8aJvvQJTv7bP61uLs96iHDtCmaTcbdk9lHYw2IweZKmc6qRmC3JPTcpOg3RD/+h0+3UIRPPgH5VJJUnjLLLft+Kxqa5AtSYA=");
        a11.setMemberId("835538755547774981");


        Account a12 = new Account();
        a12.setPhone("13110506457");
        a12.setPassword("mdSUnW1ArXtx68rpTEkvVSmWvp9hC4HjDu0JeJZUvrDVkXXZPZAjwP1K3NK/QW5igv1nhmdf/jE/fAAvdyuWlHvL1JIPCNOJMAX6jVPWc0K8a5nLvqRXenNQskfLPi9cflPFSOR8sLW18If3vIXDzXDAoigV4fUxCQJOfW0JPiU=");
        a12.setMemberId("835540602161430532");

        Account a13 = new Account();
        a13.setPhone("17058001802");
        a13.setPassword("hgxJHUqAnbtLqkSF4wTBTWidSSpc/FCUcGSf8oJWaN9cY7k0ktYmm5j1QvfIDPmZBNMixdNuFJXtwhn4deT1w7CLpJerd38l0uU3s6TfZ992i8vFcb+Sbmjcavxvzs/Z2M/xiZ432VZfkRXuiS9G8c2X850wXyQSp2IcFJe+lIc=");
        a13.setMemberId("834139434868764676");

        accountList.add(a1);
        accountList.add(a2);
        accountList.add(a3);
//        accountList.add(a4);
        accountList.add(a5);
        accountList.add(a6);
        accountList.add(a7);
        accountList.add(a8);
        accountList.add(a9);
        accountList.add(a10);
        accountList.add(a11);
        accountList.add(a12);
        accountList.add(a13);
        return accountList;
    }

    private String loginRegister(Account account) {
        String url = "https://tradeapi.jiedaibao.com/mybankv21/phppassport/v2/passport/account/loginRegister";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("JDBID", "E28F4B91-41F4-4AFB-B94E-AA946ED103F1");
        params.add("appKey", "fb371c48e9a9b2a1174ed729ae888513");
        params.add("bizType", "3");
        params.add("channel", "appstore");
        params.add("clientVersion", "2.9.8.0");
        params.add("deviceID", "00000000-0000-0000-0000-000000000000");
        params.add("deviceType", "iPhone7");
        params.add("fp", "ZQIt7XktvHRv028LP8_epA00XL5iCqQ3rGAGFo4_qZScKhPKUqM7JFx5veLkX85VIAA");
        params.add("h", "1334");
        params.add("isForeground", "1");
        params.add("isRelease", "1");
        params.add("jailbreak", "0");
        params.add("memberID", "-1");
        params.add("network", "5");
        params.add("packageName", "F6B086B48BD426A0CE8D5FCC05837D64");
        params.add("password", account.getPassword());
        params.add("phoneNumber", account.getPhone());
        params.add("phoneVen", "3");
        params.add("platform", "iOS");
        params.add("proxyType", "https");
        params.add("referer", "jdbclient://user/setting/index");
        params.add("sessionMode", "1");
        params.add("sysLaunchTimeInterval", "342528");
        params.add("systemVersion", "11.1.2");
        params.add("traceID", "B88715FD18CA46E8B10975E1E9EBA01D");
        params.add("udid", "8c107486a4b0c533e45eed182c50ba2e1e01d9e8");
        params.add("w", "750");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        ResponseEntity<JSONObject> response = client.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        return response.getBody().getJSONObject("data").getString("accessToken");
    }


    private JSONObject searchMember(Account account, String accessToken, String keyword) {
        String url = "https://tradeapi.jiedaibao.com/mybankv21/member/searchMember";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("JDBID", "E28F4B91-41F4-4AFB-B94E-AA946ED103F1");
        params.add("accessToken", accessToken);
        params.add("appKey", "fb371c48e9a9b2a1174ed729ae888513");
        params.add("channel", "appstore");
        params.add("clientVersion", "2.9.8.0");
        params.add("deviceID", "00000000-0000-0000-0000-000000000000");
        params.add("deviceType", "iPhone7");
        params.add("fp", "ZQIt7XktvHRv028LP8_epA00XL5iCqQ3rGAGFo4_qZScKhPKUqM7JFx5veLkX85VIAA");
        params.add("h", "1334");
        params.add("isForeground", "1");
        params.add("isRelease", "1");
        params.add("jailbreak", "0");
        params.add("memberID", account.getMemberId());
        params.add("network", "5");
        params.add("packageName", "F6B086B48BD426A0CE8D5FCC05837D64");
        params.add("password", account.getPassword());
        params.add("phoneNumber", account.getPhone());
        params.add("phoneVen", "3");
        params.add("platform", "iOS");
        params.add("proxyType", "https");
        params.add("referer", "jdbclient://user/setting/index");
        params.add("sessionMode", "1");
        params.add("sysLaunchTimeInterval", "342528");
        params.add("systemVersion", "11.1.2");
        params.add("traceID", "B88715FD18CA46E8B10975E1E9EBA01D");
        params.add("udid", "8c107486a4b0c533e45eed182c50ba2e1e01d9e8");
        params.add("w", "750");
        params.add("keyword", keyword);
        params.add("mask", "0");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        ResponseEntity<JSONObject> response = client.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        System.out.println(response.getBody());
        return response.getBody();
    }


    private JSONObject guest(Account account, String friendId, String accessToken) {
        String url = "https://tradeapi.jiedaibao.com/mybankv21/phptradeui/user/guest";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("JDBID", "E28F4B91-41F4-4AFB-B94E-AA946ED103F1");
        params.add("RNVersion", "2");
        params.add("accessToken", accessToken);
        params.add("appKey", "fb371c48e9a9b2a1174ed729ae888513");
        params.add("channel", "appstore");
        params.add("clientVersion", "2.9.8.0");
        params.add("containerTag", "3");
        params.add("deviceID", "00000000-0000-0000-0000-000000000000");
        params.add("deviceType", "iPhone7");
        params.add("fp", "ZQIt7XktvHRv028LP8_epA00XL5iCqQ3rGAGFo4_qZScKhPKUqM7JFx5veLkX85VIAA");
        params.add("friendID", friendId);
        params.add("h", "1334");
        params.add("isForeground", "1");
        params.add("isRelease", "1");
        params.add("jailbreak", "0");
        params.add("memberID", account.getMemberId());
        params.add("network", "5");
        params.add("packageName", "F6B086B48BD426A0CE8D5FCC05837D64");
        params.add("phoneVen", "3");
        params.add("platform", "iOS");
        params.add("proxyType", "https");
        params.add("requestTimeout", "0");
        params.add("sessionMode", "1");
        params.add("showName", "0");
        params.add("showPhone", "1");
        params.add("sysLaunchTimeInterval", "342528");
        params.add("systemVersion", "11.1.2");
        params.add("traceID", "B88715FD18CA46E8B10975E1E9EBA01D");
        params.add("udid", "8c107486a4b0c533e45eed182c50ba2e1e01d9e8");
        params.add("w", "750");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        ResponseEntity<JSONObject> response = client.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        return response.getBody();
    }

    private boolean getAuthShowList(Account account, String accessToken, String friendId) {
        JSONObject result = client.getForObject("https://tradeapi.jiedaibao.com/mybankv21/passportui/passportui/idauth/getAuthShowList?needIdauth=1,2,3,4,5,8,9,10,11,12,13,14,16,17,18,19,20,27,36" +
                "&jdbId=" + friendId +
                "&timeFlag=1" +
                "&clientVersion=2.9.8.0" +
                "&sysLaunchTimeInterval=340459" +
                "&platform=iOS" +
                "&routerKey=user/certificateAuthority" +
                "&enterTime=1519459998186" +
                "&packageName=F6B086B48BD426A0CE8D5FCC05837D64" +
                "&traceID=B88715FD18CA46E8B10975E1E9EBA01D" +
                "&h=1334&JDBID=E28F4B91-41F4-4AFB-B94E-AA946ED103F1" +
                "&appKey=fb371c48e9a9b2a1174ed729ae888513" +
                "&urlPattern=jdbclient://user/certificateAuthority" +
                "&network=5" +
                "&channel=appstore" +
                "&referer=jdbclient://user/guest/index&name" +
                "&deviceType=iPhone 7" +
                "&fp=ZQIt7XktvHRv028LP8_epA00XL5iCqQ3rGAGFo4_qZScKhPKUqM7JFx5veLkX85VIAA-kn_c-0cAyrvIzKez1_FFLRMc9JGMn4n5E7QtiNsaeR-BXhUU6urVwC5jjji-Ex-lVu6ZoCMWlF-S5YnX6eNQ3zoLNjQV" +
                "&deviceID=00000000-0000-0000-0000-000000000000" +
                "&env=prod" +
                "&systemVersion=11.1.2" +
                "&accessToken=" + accessToken +
                "&sessionMode=1" +
                "&isForeground=1" +
                "&refererValue=rn://main/userProfileGuest" +
                "&memberID=" + account.getMemberId() +
                "&proxyType=https" +
                "&w=750" +
                "&title=认证中心" +
                "&isRelease=1" +
                "&friendID=" + friendId +
                "&jailbreak=0" +
                "&udid=8c107486a4b0c533e45eed182c50ba2e1e01d9e8" +
                "&phoneVen=3", JSONObject.class);
        boolean flag = result.getJSONObject("data").getJSONObject("3").getInteger("is_auth") == 1 ? true : false;
        return flag;
    }

    //    @Scheduled(cron = "0 0 0/1 * * *")
    public void timer() {
//        System.out.println("timer");
        Page<Source> sourcePage = sourceRepository.findByIsHandle(0, new PageRequest(0, 600));
        handleSource(sourcePage.getContent());
    }


    public void handleSource(List<Source> phoneList) {
        List<Account> accountList = initAccount();
        List<Account> useList = new ArrayList<>();
        List<Source> sourceList = new ArrayList<>();
        sourceList.addAll(phoneList);
        useList.addAll(accountList);
        Iterator it = sourceList.iterator();
        while (!CollectionUtils.isEmpty(useList)) {
            Account account = useList.get(0);
            System.out.println(account.getPhone());
            String accessToken = loginRegister(account);
            while (it.hasNext()) {
                Source p = (Source) it.next();
                try {
                    JSONObject result = searchMember(account, accessToken, p.getPhone());
                    p.setIsHandle(1);
                    sourceRepository.save(p);
                    JSONArray array = result.getJSONObject("data").getJSONArray("memberList");
                    if (array != null) {
                        boolean flag = getAuthShowList(account, accessToken, array.getJSONObject(0).getString("memberID"));
                        JSONObject guest = guest(account, array.getJSONObject(0).getString("memberID"), accessToken);
                        if (flag) {
                            Boom boom = new Boom();
                            boom.setBoomId(UUID.randomUUID().toString());
                            boom.setHandleTime(new Date(System.currentTimeMillis()));
                            boom.setBorrowTip(guest.getJSONObject("data").getJSONObject("memberInfo").getJSONArray("borrowTip").getJSONObject(0).getString("text"));
                            boom.setName(guest.getJSONObject("data").getJSONObject("memberInfo").getString("memberName"));
                            boom.setPhone(p.getPhone());
                            boomRepository.save(boom);
                        }
                    }
                } catch (Exception e) {
                    useList.remove(account);
                    break;
                }
                it.remove();
            }
        }
    }

//    public static void main(String[] args) {
//        List<JieDaiBao> strList = new ArrayList<>();
//        JieDaiBao bao = new JieDaiBao();
//        bao.setPhone("123");
//        bao.setName("hey");
//
//        strList.add(bao);
//        Iterator iterator = strList.iterator();
//        while (iterator.hasNext()) {
//            JieDaiBao str = (JieDaiBao) iterator.next();
//            str.setPhone("222");
//
//            iterator.remove();
//        }
//        System.out.println(strList.size());
//
//    }

}
